const DeviceModule = {
	namespaced: true, // 启用命名空间
	state: {
		basicConfig: {
			devices: [], // 已选中的设备列表数据
		}

	},
	mutations: {

		/** 修改state 数据_测试
		 * 	payload.Name1 - state层级属性数据 如 user.info.score
		 * 	payload.data  - 赋值内容
		 *  payload.StorageName  - 缓存名称，有缓存时会开启缓存
		 *  payload.StorageData  - 缓存内容，已处理成JSON格式
		 * 	@param {object} payload  这是一个对象，包含属性名，赋值内容，缓存名、缓存内容
		 */
		ChangeAndSetStateData(state, payload) {
			// 解构出要修改的属性名
			const {
				Name1,
				data,
				StorageName,
				StorageData,
			} = payload;

			// 如果属性名存在多级，可以使用动态属性名来修改对应的值
			const levels = Name1.split('.');
			let currentState = state;
			for (let i = 0; i < levels.length - 1; i++) {
				currentState = currentState[levels[i]];
			}
			currentState[levels[levels.length - 1]] = data;

			// 根据StorageName参数来决定是否记录缓存
			if (StorageName) {
				uni.setStorageSync(StorageName, StorageData);
			}
		},


		ADD_DEVICE(state, device) {
			// 如果已存在则更新，否则新增
			const index = state.devices.basicConfig.findIndex(d => d.id === device.id)
			if (index > -1) {
				state.devices.basicConfig.splice(index, 1, {
					...state.devices.basicConfig[index],
					...device
				})
			} else {
				state.devices.basicConfig.push({
					...device,
					status: 'idle',
					data: null
				})
			}
		},

		UPDATE_STATUS(state, {
			id,
			status
		}) {
			const device = state.devices.basicConfig.find(d => d.id === id)
			if (device) device.status = status
		},

		UPDATE_DATA(state, {
			id,
			data
		}) {
			const device = state.devices.basicConfig.find(d => d.id === id)
			if (device) device.data = data
		},

		REMOVE_DEVICE(state, id) {
			state.devices.basicConfig = state.devices.basicConfig.filter(d => d.id !== id)
		},

		CLEAR_DEVICES(state) {
			state.devices.basicConfig = []
		}
	},
	actions: {
		addDevice({
			commit
		}, device) {
			commit('ADD_DEVICE', device)
		},
		updateStatus({
			commit
		}, payload) {
			commit('UPDATE_STATUS', payload)
		},
		updateData({
			commit
		}, payload) {
			commit('UPDATE_DATA', payload)
		},
		removeDevice({
			commit
		}, id) {
			commit('REMOVE_DEVICE', id)
		}




	},
	getters: {

	}
};

export default DeviceModule;